package com.newworld.dmsapp2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.litepal.crud.DataSupport;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.TelephonyManager;

import com.newworld.dmsapp2.activity.HouseManagePeopleListActivity;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleAccomplishActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleActivity;
import com.newworld.dmsapp2.activity.ToDoTaskListActivity;
import com.newworld.dmsapp2.activity.designtask.AssignAndReassignTaskActivity;
import com.newworld.dmsapp2.bean.Function;
import com.newworld.dmsapp2.bean.Task;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.SingleSample;

public class DemoUtil {
	private static String peopleType;
	public static boolean flagForServer = false;
	
	public static boolean isEmpty(String s) {
		if (null == s)
			return true;
		if (s.length() == 0)
			return true;
		if (s.trim().length() == 0)
			return true;
		return false;
	}

	@SuppressWarnings("unused")
	public static boolean showNotifation(Context context, String topic,
			String msg) {
		Map<String, String> map = new HashMap<String, String>();
		List<Function> functionList = new ArrayList<Function>();
		ArrayList<String> functionCodeList = new ArrayList<String>();
		String functionCode = null;
		User user;
		user = SingleSample.getInstance(context).getUser();
		if (user != null) {
			functionList = user.getFunctions();
			for (Function function : functionList) {
				functionCodeList.add(function.getFunctionCode());
			}

			// 户主
			if (functionCodeList
					.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFOWNER)) {
				functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFOWNER;
				peopleType = Config.HOSTER;

			}// 非户主
			else if (functionCodeList
					.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFNONOWNER)) {
				functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFNONOWNER;
				peopleType = Config.HOSTER;
			}
			// 派单员
			else if (functionCodeList
					.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {
				functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER;
				peopleType = Config.DISPATCHER;
			}// 主管
			else if (functionCodeList
					.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)) {
				functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER;
				peopleType = Config.DEPART_DISPATCHER;
			}// 维修人员
			else if (functionCodeList
					.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTSEVER)) {
				functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTSEVER;
				peopleType = Config.SERVER;
			}// 项目经理
			else if (functionCodeList
					.contains(Config.FUNCTION_REAL_GETPMPROGRESSLIST)) {
				functionCode = Config.FUNCTION_REAL_GETPMPROGRESSLIST;
				peopleType = Config.DEPART_MANAGER;
			}
			// String msg1 = msg.hashCode();
			System.out.println("msg--->" + msg);
			String[] a = msg.split(",");

			System.out.println("数组a的长度:  " + a.length);
			for (int j = 0; j < a.length; j++) {
				System.out.println("a[j]-->" + a[j]);
			}
			// System.out.println("a--->"+a);
			String messageType_typeCode = null, businessId = null, alert = null, title = null, houseFullName = null, houseId = null;
			// messageType_typeCode:xxx,businessId:xxx,alert:xxxx
			for (int i = 0; i < a.length; i++) {
				String[] b = a[i].split(":");
				if (b.length >= 2) {
					map.put(b[0], b[1]);
					if (b[0].equals("messageType_typeCode")) {
						messageType_typeCode = b[1];
					}
					if (b[0].equals("alert")) {
						alert = b[1];

					}
					if (b[0].equals("businessId")) {
						businessId = b[1];

					}
					if (b[0].equals("title")) {
						houseFullName = b[1];

					}
					if (b[0].equals("houseId")) {
						houseId = b[1];

					}
				}

			}

			// messageType_typeCode=map.get("messageType_typeCode");
			// alert=map.get("alert");
			// businessId=map.get("businessId");
			// houseFullName=map.get("title");
			try {
				Uri alarmSound = RingtoneManager
						.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

				long[] pattern = { 500, 500, 500 };
				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						context).setSmallIcon(R.drawable.logo)
						.setContentTitle(topic).setContentText(alert)
						.setSound(alarmSound).setVibrate(pattern)
						.setAutoCancel(true);

				// TODO Auto-generated method stub
				Intent i = null;
				Bundle b = new Bundle();

				// 业主消息----->服务人员已接单
				if (messageType_typeCode.equals(Config.RECEIVE_ORDER_MESSAGE)) {

					b.putString(Config.PEOPLETYPE, peopleType);

					b.putString(Config.STATUS_TYPE_CODE, Config.TYPECODE_SERVE);
					if (peopleType.equals(Config.DISPATCHER)// 派单员
							|| peopleType.equals(Config.DEPART_DISPATCHER)// 部门派单员
					) {
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_MYAPPLY);
						b.putString(Config.TASKSTATE,
								Config.TASKSTATE_DISTRIBUTED);
						i = new Intent(context,
								AssignAndReassignTaskActivity.class);
					} else if (peopleType.equals(Config.DEPART_MANAGER)) {// 项目经理
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_MYAPPLY);
						b.putString(Config.TASKSTATE,
								Config.TASKSTATE_DISTRIBUTED);
						i = new Intent(context, ServiceScheduleActivity.class);
					} else if (peopleType.equals(Config.SERVER)) {// 服务人员
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_MYAPPLY);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_TODO);
						i = new Intent(context, ServiceScheduleActivity.class);
					} else {// 业主
						b.putString(Config.FUNCTIONCODE, functionCode);
						b.putString(Config.TASKSTATE,
								Config.TASKSTATE_DISTRIBUTE);
						i = new Intent(context, ServiceScheduleActivity.class);
					}
				} // 业主消息----->维修完成，去评价（此时，只要是该角色自己提的单，都是业主身份评价）
				else if (messageType_typeCode.equals(Config.EVALUATE_MESSAGE)) {
					b.putString(Config.PEOPLETYPE, peopleType);
					b.putString(Config.FUNCTIONCODE, functionCode);
					// 户主和非户主的维修进度
					if (functionCode
							.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFOWNER)
							|| functionCode
									.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFNONOWNER)
							|| functionCode
									.equals(Config.FUNCTION_REAL_GETOUTDOORPROGRESSLISTOFOWNER)
							|| functionCode
									.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)
							|| functionCode
									.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)
							|| functionCode
									.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTSEVER)) {
						b.putString(Config.TASKSTATE, Config.TASKSTATE_DONE);
					} else {
						b.putString(Config.TASKSTATE, Config.TASKSTATE_EVALUATE);
						b.putString(Config.AREATYPE, Config.AREACODE_OUTDOOR);
					}

					if (peopleType.equals(Config.DISPATCHER)// 派单员
							|| peopleType.equals(Config.DEPART_DISPATCHER)// 部门派单员
					) {
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_MYAPPLY);
					} else if (peopleType.equals(Config.DEPART_MANAGER)) {// 项目经理
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_MYAPPLY);
					} else if (peopleType.equals(Config.SERVER)) {// 服务人员
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_MYAPPLY);
					} else {// 业主
						b.putString(Config.FUNCTIONCODE, functionCode);
					}

					b.putString(Config.STATUS_TYPE_CODE,
							Config.TYPECODE_EVALUATE);
					i = new Intent(context,
							ServiceScheduleAccomplishActivity.class);

				} // 派单员消息----->业主提单
				else if (messageType_typeCode
						.equals(Config.REPAIR_APPLY_MESSAGE)) {
					// 派单员
					b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
					b.putString(Config.FUNCTIONCODE,
							Config.FUNCTION_REAL_GETDISPATCHTASKLIST);
					b.putString(Config.TASKSTATE,
							Config.TASKSTATE_NOTDISTRIBUTE);
					i = new Intent(context, AssignAndReassignTaskActivity.class);

				}// 派单员消息----->业主催单（一级派单流程）
				else if (messageType_typeCode
						.equals(Config.REMIND_MESSAGE_FOR_DISPATCHER)) {
					// 派单员
					b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
					b.putString(Config.FUNCTIONCODE,
							Config.FUNCTION_REAL_GETREDISPATCHTASKLIST);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_BEASKED);
					i = new Intent(context, AssignAndReassignTaskActivity.class);
				}
				// 派单员消息----->超时督办
				else if (messageType_typeCode.equals(Config.SUPERVISE_MESSAGE)) {
					// 派单员
					b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
					b.putString(Config.FUNCTIONCODE, functionCode);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_DUBAN);
					i = new Intent(context, AssignAndReassignTaskActivity.class);

				}// 派单员消息----->申请改派
				else if (messageType_typeCode
						.equals(Config.MANAGER_REDISPATCH_MESSAGE)) {
					// 派单员
					b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
					b.putString(Config.FUNCTIONCODE, functionCode);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_APPLYCHANGE);
					i = new Intent(context, AssignAndReassignTaskActivity.class);

				}// 派单员消息----->回访
				else if (messageType_typeCode.equals(Config.REVISIT_MESSAGE)) {
					// 派单员
					b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
					b.putString(Config.FUNCTIONCODE, functionCode);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_REVISIT);
					b.putString(Config.STATUS_TYPE_CODE,
							Config.TYPECODE_REVISIT);
					i = new Intent(context,
							ServiceScheduleAccomplishActivity.class);

				}
				// 主管消息----->已派单
				else if (messageType_typeCode
						.equals(Config.SERVE_MESSAGE_FOR_MANAGER)) {
					// 主管
					b.putString(Config.PEOPLETYPE, Config.DEPART_DISPATCHER);
					b.putString(Config.FUNCTIONCODE,
							Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST);
					b.putString(Config.TASKSTATE,
							Config.TASKSTATE_NOTDISTRIBUTE);
					i = new Intent(context, AssignAndReassignTaskActivity.class);

				}// 主管消息----->业主催单
				else if (messageType_typeCode
						.equals(Config.REMIND_MESSAGE_FOR_MANAGER)) {
					// 主管
					b.putString(Config.PEOPLETYPE, Config.DEPART_DISPATCHER);
					b.putString(Config.FUNCTIONCODE,
							Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_BEASKED);
					i = new Intent(context, AssignAndReassignTaskActivity.class);

				}// 主管消息----->已被改派
				else if (messageType_typeCode
						.equals(Config.SERVE_ONLY_SEE_MESSAGE)) {

				}// 主管消息----->申请改派
				else if (messageType_typeCode
						.equals(Config.SERVER_REDISPATCH_MESSAGE)) {
					// 主管
					b.putString(Config.PEOPLETYPE, Config.DEPART_DISPATCHER);
					b.putString(Config.FUNCTIONCODE,
							Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_APPLYCHANGE);
					i = new Intent(context, AssignAndReassignTaskActivity.class);

				}// 服务人员消息----->已派单
				else if (messageType_typeCode
						.equals(Config.SERVE_MESSAGE_FOR_SERVER)) {
					// 服务人员
					flagForServer = true;
					DemoReceiver.count++;
					b.putString(Config.PEOPLETYPE, Config.SERVER);

					List<Task> localTasks = DataSupport.where(
							"repairId = ? and user_id = ?", businessId,
							String.valueOf(user.getId())).find(Task.class);
					if (localTasks.size() > 0) {
						Task localTask = localTasks.get(0);
						b.putString(Config.TASKSTATE, localTask.getTaskState());
						b.putString(Config.STATUS_TYPE_CODE,
								localTask.getStatusType_typeCode());
						if (localTask.getTaskState().equals(
								Config.TASKSTATE_TOPOST)) {
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETREPAIRTASKLIST);
							i = new Intent(context,
									ServiceScheduleAccomplishActivity.class);
						} else {
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETREPAIRTASKLIST);
							i = new Intent(context,
									ServiceScheduleActivity.class);
						}
					} else {
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETREPAIRTASKLIST);
						b.putString(Config.TASKSTATE,
								Config.TASKSTATE_TORECEIVEORDER);
						b.putString(Config.STATUS_TYPE_CODE,
								Config.TYPECODE_RECEIVEORDER);
						b.putString(Config.PEOPLETYPE, Config.SERVER);
						i = new Intent(context, ServiceScheduleActivity.class);
					}

				}// 服务人员消息----->业主催单
				else if (messageType_typeCode
						.equals(Config.REMIND_MESSAGE_FOR_SERVER)) {
					// 服务人员
					flagForServer = true;
					DemoReceiver.count++;
					b.putString(Config.PEOPLETYPE, Config.SERVER);
					b.putString(Config.TASKSTATE, Config.TASKSTATE_BEASKED);
					b.putString(Config.STATUS_TYPE_CODE, Config.TYPECODE_SERVE);
					b.putString(Config.FUNCTIONCODE,
							Config.FUNCTION_REAL_GETREPAIRTASKLIST);
					i = new Intent(context, ServiceScheduleActivity.class);
				}
				// 房屋关联申请
				else if (messageType_typeCode
						.equals(Config.WAIT_RELATE_MESSAGE)) {
					b.putString("houseUserId", houseId);
					i = new Intent(context, HouseManagePeopleListActivity.class);

				}// 已获得户主同意\未获得户主同意
				else if (messageType_typeCode
						.equals(Config.RELATE_ONLY_MESSAGE)) {

				}// 系统消息
				else if (messageType_typeCode.equals(Config.SYSTEM_MESSAGE)) {

				}
				b.putString(Config.HOUSEID, houseId);
				b.putString(Config.REPAIRID, businessId);
				b.putString(Config.HOUSEFULLNAME, houseFullName);

				if (i != null) {
					i.putExtras(b);
				}
				// Intent resultIntent = new Intent(context,MainActivity.class);
				//
				// resultIntent.putExtra(Config.REPAIRID, businessId);
				// Creates an explicit intent for an Activity in your app

				// The stack builder object will contain an artificial back
				// stack
				// for the
				// started Activity.
				// This ensures that navigating backward from the Activity leads
				// out
				// of
				// your application to the Home screen.
				TaskStackBuilder stackBuilder = TaskStackBuilder
						.create(context);
				// Adds the back stack for the Intent (but not the Intent
				// itself)
				stackBuilder.addParentStack(ToDoTaskListActivity.class);
				// Adds the Intent that starts the Activity to the top of the
				// stack

				// stackBuilder.addNextIntent(resultIntent);
				stackBuilder.addNextIntent(i);
				PendingIntent resultPendingIntent = stackBuilder
						.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager mNotificationManager = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				// mId allows you to update the notification later on.
				Random r = new Random();
				mNotificationManager.notify(r.nextInt(), mBuilder.build());
			} catch (Exception e) {
				return false;
			}
		}
		return true;
	}

	public static void showToast(final String toast, final Context context) {
		// if (!isAppOnForeground(context)) return;
		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// Looper.prepare();
		// Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
		// Looper.loop();
		// }
		// }).start();
	}

	public static boolean isAppOnForeground(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		// Returns a list of application processes that are running on the
		// device
		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;
		for (RunningAppProcessInfo appProcess : appProcesses) {
			// importance:
			// The relative importance level that the system places
			// on this process.
			// May be one of IMPORTANCE_FOREGROUND, IMPORTANCE_VISIBLE,
			// IMPORTANCE_SERVICE, IMPORTANCE_BACKGROUND, or IMPORTANCE_EMPTY.
			// These constants are numbered so that "more important" values are
			// always smaller than "less important" values.
			// processName:
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(context.getPackageName())
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}
		return false;
	}

	public static <T> String join(T[] array, String cement) {
		StringBuilder builder = new StringBuilder();

		if (array == null || array.length == 0) {
			return null;
		}
		for (T t : array) {
			builder.append(t).append(cement);
		}

		builder.delete(builder.length() - cement.length(), builder.length());

		return builder.toString();
	}

	public static boolean isNetworkEnabled(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conn.getActiveNetworkInfo();
		return (info != null && info.isConnected());
	}

	public static String getImei(Context context, String imei) {
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		imei = telephonyManager.getDeviceId();
		return imei;
	}

	public static String getAppKey(Context context) {
		Bundle metaData = null;
		String appKey = null;
		try {
			ApplicationInfo ai = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);
			if (null != ai) {
				metaData = ai.metaData;
			}
			if (null != metaData) {
				appKey = metaData.getString("YUNBA_APPKEY");
				if ((null == appKey) || appKey.length() != 24) {
					appKey = "Error";
				}
			}
		} catch (NameNotFoundException e) {

		}
		return appKey;
	}
}
